package com.wjm.databaseframework.db;

import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;

import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class BaseDaoFactory {
    private static final BaseDaoFactory ourInstance = new BaseDaoFactory();

    public static BaseDaoFactory getOurInstance() {
        return ourInstance;
    }

    private SQLiteDatabase sqLiteDatabase;
    //设计一个数据库连接池
    protected Map<String,BaseDao> map= Collections.synchronizedMap(new HashMap<String, BaseDao>());

    ///storage/emulated/0
///test.db
    protected BaseDaoFactory() {
//        File esd = Environment.getExternalStorageDirectory();
        //建议写入SD卡
        File file=new File(Environment.getExternalStorageDirectory(),"update");
        if(!file.exists()) {
            file.mkdirs();
        }
        String sqliteDatabasePath = file.getAbsolutePath()+"/user.db";
//        String sqliteDatabasePath = esd.getAbsolutePath()+"/test.db";
        sqLiteDatabase = SQLiteDatabase.openOrCreateDatabase(sqliteDatabasePath, null);
    }

    public <T> BaseDao<T> getBaseDao(Class<T> entityClass) {
        BaseDao baseDao = null;
        try {
            baseDao = BaseDao.class.newInstance();
            baseDao.init(sqLiteDatabase, entityClass);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return baseDao;
    }
    /**
     * 用来生产basedao对象
     * M  User
     * T  BaseDao
     */
    public  <T extends BaseDao<M>,M> T  getBaseDao(Class<T> daoClass,Class<M> entityClass){
        BaseDao baseDao=null;
        try {
            baseDao=daoClass.newInstance();
            baseDao.init(sqLiteDatabase,entityClass);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return (T)baseDao;
    }

}
//07-30 10:32:05.834 8201-8201/com.wjm.databaseframework E/SQLiteDatabase: Failed to open database 'data/data/com.wjm.databaseframework/test.db'.
//        android.database.sqlite.SQLiteDiskIOException: disk I/O error (code 522 SQLITE_IOERR_SHORT_READ): , while compiling: PRAGMA journal_mode